#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
价格一致性测试脚本
验证同一股票多次获取价格是否一致
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from real_data_fetcher import RealDataFetcher
import time

def test_price_consistency():
    """测试价格一致性"""
    print("🔍 价格一致性测试")
    print("="*50)
    
    test_stock = "000001"  # 测试股票
    
    print(f"📊 测试股票: {test_stock}")
    print(f"🔄 测试方案:")
    print(f"   1. 同一实例多次获取")
    print(f"   2. 不同实例多次获取")
    print(f"   3. 间隔时间获取")
    print()
    
    # 测试1: 同一实例多次获取
    print("🧪 测试1: 同一实例多次获取价格")
    fetcher1 = RealDataFetcher()
    
    prices_same_instance = []
    for i in range(3):
        data = fetcher1.get_stock_data(test_stock, 5)
        if not data.empty:
            current_price = data['close'].iloc[-1]
            prices_same_instance.append(current_price)
            print(f"   第{i+1}次: {current_price:.2f}元")
    
    # 测试2: 不同实例多次获取
    print("\n🧪 测试2: 不同实例多次获取价格")
    prices_diff_instance = []
    for i in range(3):
        fetcher = RealDataFetcher()  # 每次创建新实例
        data = fetcher.get_stock_data(test_stock, 5)
        if not data.empty:
            current_price = data['close'].iloc[-1]
            prices_diff_instance.append(current_price)
            print(f"   第{i+1}次: {current_price:.2f}元")
    
    # 测试3: 获取股票基本信息中的价格
    print("\n🧪 测试3: 获取基本信息中的价格")
    prices_basic_info = []
    for i in range(3):
        fetcher = RealDataFetcher()
        info = fetcher.get_stock_basic_info(test_stock)
        price = info.get('current_price', 0)
        prices_basic_info.append(price)
        print(f"   第{i+1}次: {price:.2f}元")
    
    # 结果分析
    print("\n📊 结果分析:")
    print(f"   同一实例价格一致性: {len(set(prices_same_instance)) == 1}")
    print(f"   不同实例价格一致性: {len(set(prices_diff_instance)) == 1}")
    print(f"   基本信息价格一致性: {len(set(prices_basic_info)) == 1}")
    
    print(f"\n📈 价格详情:")
    print(f"   同一实例: {prices_same_instance}")
    print(f"   不同实例: {prices_diff_instance}")
    print(f"   基本信息: {prices_basic_info}")
    
    # 差异分析
    if len(set(prices_diff_instance)) > 1:
        max_price = max(prices_diff_instance)
        min_price = min(prices_diff_instance)
        diff_pct = (max_price - min_price) / min_price * 100
        print(f"\n⚠️ 价格差异:")
        print(f"   最大差异: {diff_pct:.2f}%")
        print(f"   最高价: {max_price:.2f}元")
        print(f"   最低价: {min_price:.2f}元")
    
    return {
        'same_instance_consistent': len(set(prices_same_instance)) == 1,
        'diff_instance_consistent': len(set(prices_diff_instance)) == 1,
        'basic_info_consistent': len(set(prices_basic_info)) == 1,
        'prices_same_instance': prices_same_instance,
        'prices_diff_instance': prices_diff_instance,
        'prices_basic_info': prices_basic_info
    }

def test_multiple_stocks():
    """测试多只股票的一致性"""
    print("\n🧪 测试4: 多只股票价格一致性")
    
    test_stocks = ["000001", "000002", "600036"]
    
    for stock_code in test_stocks:
        print(f"\n📊 测试股票: {stock_code}")
        
        # 两次获取同一股票
        fetcher1 = RealDataFetcher()
        fetcher2 = RealDataFetcher()
        
        price1 = fetcher1.get_stock_basic_info(stock_code).get('current_price', 0)
        price2 = fetcher2.get_stock_basic_info(stock_code).get('current_price', 0)
        
        print(f"   第1次: {price1:.2f}元")
        print(f"   第2次: {price2:.2f}元")
        print(f"   是否一致: {price1 == price2}")
        
        if price1 != price2:
            diff_pct = abs(price1 - price2) / min(price1, price2) * 100
            print(f"   差异: {diff_pct:.2f}%")

if __name__ == "__main__":
    print("🎯 开始价格一致性测试...")
    
    # 主要测试
    result = test_price_consistency()
    
    # 多股票测试
    test_multiple_stocks()
    
    print("\n" + "="*50)
    print("🎯 测试完成！")
    
    if not result['diff_instance_consistent']:
        print("❌ 发现问题: 不同实例获取的价格不一致")
        print("💡 问题原因: 每个实例使用不同的随机数种子")
    else:
        print("✅ 价格获取一致性正常")
